
package com.the9tcat.deliverycoming;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adview.AdViewLayout;
import com.mobclick.android.MobclickAgent;
import com.the9tcat.deliverycoming.data.Configure;
import com.the9tcat.deliverycoming.db.DeliveryDb;
import com.the9tcat.deliverycoming.modle.DeliveryDetail;
import com.the9tcat.deliverycoming.modle.DeliveryInfo;
import com.the9tcat.deliverycoming.modle.NotificationCenter;
import com.the9tcat.deliverycoming.net.HttpClient;
import com.the9tcat.deliverycoming.util.Logger;

public class DeliveryDetailActivity extends Activity {

    private TextView t_delivery_number;

    private TextView t_delivery_company;

    private TextView t_title;
    
    private Toast toast;
    
    private LinearLayout Layout_status_area;
    
    private RelativeLayout layout_detail_content;

    private ImageView img_sign;
    
    private ImageView img_latest_status;
    
    private Button b_refresh;
    
    DeliveryDb db;

    private int mTrackId;
    
    DeliveryInfo delivery;
    
    boolean isRun = true;
    
    boolean isInUpdate = false;
    
    boolean from_notice = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(Configure.getInstance(this).getAdPositionIndex()==0){
        	this.setContentView(R.layout.delivery_detail);
        }else{
        	this.setContentView(R.layout.delivery_detail_bottom);
        }
        toast = Toast.makeText(this, getString(R.string.noupdate), Toast.LENGTH_SHORT);
        t_delivery_number = (TextView) findViewById(R.id.delivery_number);
        t_delivery_company = (TextView) findViewById(R.id.delivery_company);
        Layout_status_area = (LinearLayout) findViewById(R.id.status_area);
        layout_detail_content = (RelativeLayout) findViewById(R.id.detail_content);
        t_title = (TextView) findViewById(R.id.t_title);
        img_sign = (ImageView) findViewById(R.id.img_sign);
        b_refresh = (Button) findViewById(R.id.b_refresh);
//        t_sign_date = (TextView) findViewById(R.id.t_sign_date);
        
        //判断是否从notification启动
        Intent i_from = getIntent();
        
        // 得到详细信息
        mTrackId = i_from.getIntExtra("trackId", -1);
        Logger.d("***", "id " + mTrackId);
        String from_activity = i_from.getStringExtra("ACTIVITY_NAME_KEY");
        if(from_activity!=null&&from_activity.equals("notification")){
            from_notice = true;
        } else {
            // 不是从Noti进来的，就删除Noti
            NotificationCenter.getNotificationCenter(this).removeNotification(mTrackId);
        }
        
        //db = new DeliveryDb(this);
        db = DeliveryDb.getDb(this);
        //db.open();
        delivery = db.getDelivery(mTrackId);
//        setTestData();
        registerButtonSign();
        registerButtonRefresh();
        setDetail();
        
        // 闪烁箭头
        flashArrow();
        
        //ads
        initAd();
    }
    
    private void initAd() {
        LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
        if (layout == null) 
            return;
        /*delete these two line when release*/
//        AdViewTargeting.setUpdateMode(UpdateMode.EVERYTIME); 
//        AdViewTargeting.setRunMode(RunMode.TEST);  
        //        
        AdViewLayout adViewLayout = new AdViewLayout(this, "SDK20112322270845e21nvjcswpn3cod");
        RelativeLayout.LayoutParams adViewLayoutParams = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
        layout.addView(adViewLayout, adViewLayoutParams);
        
        layout.invalidate();
       
    }
    
    public void flashArrow(){
    	 // 闪动箭头
        new AsyncTask<Integer, Integer, Integer>(){
            @Override
            protected Integer doInBackground(Integer... params) {
                int i = 0;
                while (isRun) {
                    if (img_latest_status != null) {
                        i = (++i) % 2;
                        this.publishProgress(i);
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return null;
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                if (values[0].intValue() == 0) {
                    img_latest_status.setBackgroundResource(R.drawable.status_arrow);
                } else {
                    img_latest_status.setBackgroundResource(R.drawable.status_arrow2);
                }
                super.onProgressUpdate(values);
            }
        }.execute(new Integer[] {});
    }
    
    @Override
    protected void onDestroy() {
        isRun = false;
        db.close();
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }


	@Override
    protected void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
    }

	private void registerButtonRefresh() {
        b_refresh.setOnClickListener(new View.OnClickListener() {
        	ProgressDialog pd;
            @Override
            public void onClick(View v) {
            	pd = new ProgressDialog(DeliveryDetailActivity.this);
            	pd.cancel();
            	pd.setMessage("正在更新...");
            	pd.show();
//            	if (isInUpdate) {
//            		return;
//            	}
//            	b_refresh.setSelected(true);
                new AsyncTask<Void, Void, Bitmap>() {
                    @Override
                    protected Bitmap doInBackground(Void... params) {
                    	isInUpdate = true;
                    	return HttpClient.newInstance().checkValicode(delivery);
//                        HttpClient.newInstance().updateDeliveryDetails(delivery, null);
                        // update database.
//                        return db.update(delivery);
                    }

                    @Override
                    protected void onPostExecute(Bitmap result) {
                        if (result != null) {
                        	
                        	pd.dismiss();
							AlertDialog.Builder b = new AlertDialog.Builder(DeliveryDetailActivity.this);
							LinearLayout ll = new LinearLayout(DeliveryDetailActivity.this);
							ll.setOrientation(LinearLayout.VERTICAL);
							ll.setGravity(Gravity.CENTER);
							ImageView iv = new ImageView(DeliveryDetailActivity.this);
							iv.setImageBitmap(result);
							ll.addView(iv);
							final EditText et = new EditText(DeliveryDetailActivity.this);
							
							LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(200, -1);
							et.setLayoutParams(lp);
							ll.addView(et);
							b.setTitle("请输入验证码").setView(ll);
							b.setPositiveButton("确定", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface arg0, int arg1) {
									
									new Thread(){
					                	public void run(){
					                		boolean updated = HttpClient.newInstance().updateDeliveryDetails(delivery, et.getText().toString());
					                		if(updated){
												db.update(delivery);
											}
					                		
					                		if (updated) {
					                			setDetail();
					                            toast.setText("最新状态:"+delivery.getDetail().get(0).getStatus());
					                            toast.show();
					                		} else {
					                			toast.setText(R.string.noupdate);
					                        	toast.show();
					                		}
					                	}
					                }.start();
								}
							});
							b.create().show();
                        } else {
                        	new AsyncTask<Void, Void, Boolean>() {
								@Override
								protected Boolean doInBackground(Void... params) {
									boolean updated = HttpClient.newInstance().updateDeliveryDetails(delivery, null);
									if(updated){
										db.update(delivery);
									}
        	                		delivery = db.getDelivery(mTrackId);
									return updated;
								}

								@Override
								protected void onPostExecute(Boolean result) {
									super.onPostExecute(result);
									if (result) {
        	                			setDetail();
        	                            toast.setText("最新状态:"+delivery.getDetail().get(0).getStatus());
        	                            toast.show();
        	                		} else {
        	                			toast.setText(R.string.noupdate);
        	                        	toast.show();
        	                		}
//        	                		isInUpdate = false;;
//        	                        b_refresh.setSelected(false);
        	                        pd.dismiss();
								}
								
                        	}.execute(new Void[] {});
                        }
                    }
                }.execute(new Void[]{});
            }
        });
    }
    
    @Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && from_notice) {
			Intent to_list = new Intent(DeliveryDetailActivity.this,DeliveryComingActivity.class);
			
			// 解决从主列表选择通知栏进入详细后返回时的问题
			to_list.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(to_list);
			finish();
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void registerButtonSign() {
    	img_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
                    AlertDialog.Builder builder = new AlertDialog.Builder(DeliveryDetailActivity.this);
                    if (!delivery.isSigned()) {
                    	builder.setTitle(R.string.dialog_sign_title).setMessage(R.string.dialog_sign_info);
                    }else{
                    	builder.setTitle(R.string.dialog_unsign_title).setMessage(R.string.dialog_unsign_info);
                    }
                    builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        	if (!delivery.isSigned()) {
	                            db.updateSigned(mTrackId, 1);
	                            delivery.setSigned(true);
	                            isRun = false;
	                            if (img_latest_status != null) {
	                                img_latest_status.setBackgroundResource(R.drawable.status_arrow2);
	                            }
	                            img_sign.setImageResource(R.drawable.signed);
	                            b_refresh.setVisibility(View.GONE);
                        	} else {
                        		db.updateSigned(mTrackId, 0);
                        		delivery.setSigned(false);
                        		
                        		if (img_latest_status != null) {
	                                img_latest_status.setBackgroundResource(R.drawable.status_arrow);
	                            }
                        		img_sign.setImageResource(R.drawable.drawing_pen);
                        		b_refresh.setVisibility(View.VISIBLE);
                        		
                        		//开始闪烁箭头
                        		isRun = true;
                        		flashArrow();
                        	}
                        }
                    });
                    builder.setNegativeButton(R.string.button_cancel, null);
                    builder.create().show();
                }
            
        });
    }

    private void setDetail() {
        if (mTrackId >= 0) {
            if (delivery != null) {
                t_delivery_number.setText(getText(R.string.t_nu) + delivery.getExpressNu());
                t_delivery_company.setText(getText(R.string.t_com) + delivery.getExpComName());
                ArrayList<DeliveryDetail> detail = new ArrayList<DeliveryDetail>();
                
                // Set the color
                switch(delivery.getColor()){
                case DeliveryInfo.COLOR_BLUE:
                	layout_detail_content.setBackgroundResource(R.drawable.bg_blue);
                	break;
                case DeliveryInfo.COLOR_GREEN:
                	layout_detail_content.setBackgroundResource(R.drawable.bg_green);
                	break;
                case DeliveryInfo.COLOR_YELLOW:
                	layout_detail_content.setBackgroundResource(R.drawable.bg_yellow);
                	break;
                }
                t_title.setText(delivery.getName());
                detail = delivery.getDetail();
                Layout_status_area.removeAllViews();
                if (detail!=null) {
                    LayoutInflater inflater = LayoutInflater.from(this);
                    for (int i = 0; i < detail.size(); i++) {
                        LinearLayout statusLayout = (LinearLayout) inflater.inflate(R.layout.detail_status_item, null);
                        ((ImageView) statusLayout.findViewById(R.id.img_icon)).setBackgroundResource(R.drawable.status_arrow);
                        if (i == 0) {
                            img_latest_status = (ImageView) statusLayout.findViewById(R.id.img_icon);
                        }
                        ((TextView) statusLayout.findViewById(R.id.t_date)).setText(detail.get(i).getTime().replaceAll(" {2,}", " "));
                        ((TextView) statusLayout.findViewById(R.id.t_status)).setText(detail.get(i).getStatus().replaceAll(" {2,}", " "));
                        Layout_status_area.addView(statusLayout);
                    }
                } else {
                    TextView t_status = new TextView(this);
                    t_status.setText(getResources().getString(R.string.delivery_msg_noStatus));
                    Layout_status_area.addView(t_status);
                }
                
                if (delivery.isSigned()) {
                    img_sign.setImageResource(R.drawable.signed);
                    b_refresh.setVisibility(View.GONE);
                    isRun = false;
                    if (img_latest_status != null) {
                        img_latest_status.setBackgroundResource(R.drawable.status_arrow2);
                    }
                }
            }

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem itemDelete = menu.add(R.string.menu_delete);
        itemDelete.setIcon(R.drawable.icon_del);
        MenuItem itemShare = menu.add(R.string.menu_share);
        itemShare.setIcon(R.drawable.icon_share);
        itemDelete.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                AlertDialog.Builder builder = new AlertDialog.Builder(DeliveryDetailActivity.this);
                builder.setTitle(R.string.dialog_delete_title).setMessage(R.string.dialog_delete_info);
                builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        db.delete(mTrackId);
                    }
                });
                builder.setNegativeButton(R.string.button_cancel, null);
                builder.create().show();
                return false;
            }
        });
        itemShare.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            
            int index = 0;
            
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                final String status = delivery.getLatestStatus();
                
                if (TextUtils.isEmpty(status)) {
                    Toast.makeText(getApplicationContext(), R.string.t_share_noinfo, Toast.LENGTH_LONG).show();
                    return false;
                }
                // 分享
                AlertDialog.Builder builder = new AlertDialog.Builder(DeliveryDetailActivity.this);
                builder.setSingleChoiceItems(new CharSequence[] {getText(R.string.t_share_sms), getText(R.string.t_share_email)}, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        index = which;
                    }
                });
                builder.setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (index == 0) {
                            // 跑到短信界面
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.putExtra("sms_body", delivery.getName() + "\n" + status);
                            intent.setType("vnd.android-dir/mms-sms");
                            startActivity(intent);
                        } else if (index == 1) {
                            // 跑到邮件界面
                            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"));
                            ArrayList<DeliveryDetail> al = delivery.getDetail();
                            String detail = "";
                            for(DeliveryDetail item:al) {
                            	detail += (item.getStatus().replaceAll(" {2,}", " ") + "\n");
                            }
                            intent.putExtra(Intent.EXTRA_TEXT, detail);
                            intent.putExtra(Intent.EXTRA_SUBJECT, delivery.getName());
                            startActivity(intent);
                        }
                    }
                });
                builder.setNegativeButton(R.string.button_cancel, null);
                builder.create().show();
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }
}
